package com.statistics.thread;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.statistics.bean.Electricity;
import com.statistics.bean.MaxCurrentPower;
import com.statistics.cloudpower.dao.TblElectricityStatisticsDayDAO;
import com.statistics.cloudpower.dao.TblElectricityStatisticsMonthDAO;
import com.statistics.cloudpower.entity.TblElectricityStatisticsDay;
import com.statistics.cloudpower.entity.TblElectricityStatisticsMonth;
import com.statistics.cloudpower.entity.TblEquipment;
import com.statistics.tools.Constants;
import com.statistics.tools.Tools;
import com.statistics.yfdata.dao.DataElectricityRepository;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 电量统计线程
 * Created by studio on 2017/4/6.
 */

@Component
@Scope("prototype")
public class ElectricityStatisticsThread extends Thread {

    private Logger logger;
    private String uuid;
    private String command;
    private List<TblEquipment> obj;
    private int fragment_number;
    private TblElectricityStatisticsDayDAO tblElectricityStatisticsDayDAO;
    private TblElectricityStatisticsMonthDAO tblElectricityStatisticsMonthDAO;
    private DataElectricityRepository dataElectricityRepository;
    private String month;


    public ElectricityStatisticsThread(String command, List<TblEquipment> obj,
                                       Object dao, String uuid, int fragment_number,
                                       DataElectricityRepository dataElectricityRepository,
                                       String month) {

        this.command = command;
        this.obj = obj;
        this.fragment_number = fragment_number;
        this.uuid = uuid;
        this.dataElectricityRepository = dataElectricityRepository;
        this.month = month;

        switch (command) {
            case Constants.EVERY_DAY:
                this.logger = Logger.getLogger("电量日统计");
                this.tblElectricityStatisticsDayDAO = (TblElectricityStatisticsDayDAO) dao;
                break;
            case Constants.EVERY_MONTH:
                this.logger = Logger.getLogger("电量月统计");
                this.tblElectricityStatisticsMonthDAO = (TblElectricityStatisticsMonthDAO) dao;
                break;
        }
    }

    @Override
    public void run() {

        //根据读取的command进行相应运算
        try {
            DateFormat dataFormat = DateFormat.getDateInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String thread_start_time = simpleDateFormat2.format(new Date());

            String now = dataFormat.format(new Date());
            Date today = simpleDateFormat.parse(now);
            Long start_date = (long) 0;//前一天起始时间的时间戳
            Long end_date = (long) 0;//前一天结束时间的时间戳

            List<TblEquipment> tblEquipment = obj;
            List records = null;
            int equipment_number;


            switch (command) {
                case Constants.EVERY_DAY:

                    //每日电量统计
                    start_date = today.getTime() - 24 * 3600 * 1000;
                    end_date = today.getTime();
//                    start_date = today.getTime() ;
//                    end_date = today.getTime()+ 24 * 3600 * 1000;

                    System.err.println("start_date:"+start_date);
                    System.err.println("end_date:"+end_date);
                    records = new ArrayList<TblElectricityStatisticsDay>();
                    break;
                case Constants.EVERY_MONTH:

                    //每月电量统计
                    Calendar first_day = Calendar.getInstance();
                    first_day.add(Calendar.MONTH, -1);
                    first_day.set(Calendar.DAY_OF_MONTH, 1);

                    Calendar last_day = Calendar.getInstance();
                    last_day.set(Calendar.DAY_OF_MONTH, 1);
                    start_date = simpleDateFormat.parse(dataFormat.format(first_day.getTime())).getTime();
                    end_date = simpleDateFormat.parse(dataFormat.format(last_day.getTime())).getTime();

                    records = new ArrayList<TblElectricityStatisticsMonth>();

                    break;
            }

            if (records == null) {
                return;
            }

            //对这n条设备数据逐条进行查找相应的电量列表
            for (equipment_number = 0; equipment_number < tblEquipment.size(); equipment_number++) {
                JSONArray jsonArray = new JSONArray();

                if (tblEquipment.get(equipment_number) == null) {
                    continue;
                }

                //取得头尾数据差值
                String mac = tblEquipment.get(equipment_number).getMac();

                Electricity electricity = dataElectricityRepository.getSubtraction(mac, start_date, end_date, month);
                MaxCurrentPower maxCurrentPower = dataElectricityRepository.getMaxCurrentPower(mac, start_date, end_date, month);

                if (electricity == null) {
                    //没有这条设备记录
                    continue;
                }

                //获取8个房间各自的当天用电量
                for (int offset = 1; offset < 9; offset++) {

                    Double d_value = Double.parseDouble(electricity.getRoomElectricity(offset));
                    BigDecimal total_electricity = new BigDecimal((d_value) * 0.01);

                    Double d_maxCurrent = Double.parseDouble(maxCurrentPower.getRoomCurrent(offset));
                    BigDecimal max_current = new BigDecimal((d_maxCurrent) * 0.01);

                    Double d_maxPower = Double.parseDouble(maxCurrentPower.getRoomPower(offset));
                    BigDecimal max_power = new BigDecimal((d_maxPower) * 0.01);

                    switch (command) {
                        case Constants.EVERY_DAY: {
                            TblElectricityStatisticsDay one_record = new TblElectricityStatisticsDay();
                            one_record.setMac(mac);
                            one_record.setOffset(offset);
                            one_record.setTotalElectricity(total_electricity);
                            one_record.setStatisticsTime(new Timestamp(start_date));
                            one_record.setMax_current(max_current);
                            one_record.setMax_power(max_power);

                            records.add(one_record);
                            break;
                        }
                        case Constants.EVERY_MONTH: {
                            TblElectricityStatisticsMonth one_record = new TblElectricityStatisticsMonth();
                            one_record.setMac(mac);
                            one_record.setOffset(offset);
                            one_record.setTotalElectricity(total_electricity);
                            one_record.setStatisticsTime(new Timestamp(start_date));
                            one_record.setMax_current(max_current);
                            one_record.setMax_power(max_power);
                            records.add(one_record);
                            break;
                        }
                    }
                    JSONObject jsonObject = Tools.getJsonEleStr(mac,offset,total_electricity,max_current,max_power,start_date);
                    jsonArray.add(jsonObject);

                }
                switch (command) {
                    case Constants.EVERY_DAY:
                        Tools.sendTo61(Constants.DIANBIAODAY,jsonArray.toJSONString());
                        break;
                    case Constants.EVERY_MONTH:
//                        Tools.sendTo61(Constants.DIANBIAOMONTH,jsonArray.toJSONString());
                        break;
                }
            }

            switch (command) {
                case Constants.EVERY_DAY:
                    tblElectricityStatisticsDayDAO.save(records);
                    break;
                case Constants.EVERY_MONTH:
                    tblElectricityStatisticsMonthDAO.save(records);
                    break;
            }



            records.clear();

            String thread_end_time = simpleDateFormat2.format(new Date());
            logger.info(uuid + " 第" + fragment_number + "分片 Count=" + equipment_number + " Start=" + thread_start_time + " End=" + thread_end_time);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
}
